import json
from datetime import datetime

from django import http

from django.shortcuts import render
from django.views import View

from meidou_mall.apps.goods.models import SKU, SPU, GoodsCategory, CategoryVisitCount
from meidou_mall.utils import constants
from meidou_mall.utils.my_category import get_categories
from django.core.paginator import Paginator

from meidou_mall.utils.my_loginview import LoginRequiredView
from meidou_mall.utils.response_code import RET
from django_redis import get_redis_connection


# Create your views here.

class GoodsListView(View):

    def get(self, request, category_id, page):
        sort = request.GET.get('sort', 'default')
        sort_field = 'default'
        if sort == 'price':
            sort_field = 'price'
        elif sort == 'hot':
            sort_field = 'sales'
        else:
            sort_field = 'create_time'

        categories = get_categories()

        skus_all = SKU.objects.filter(category_id=category_id).order_by(sort_field).all()
        paginator = Paginator(skus_all, constants.SKU_LIST_PAGE_COUNT)
        page = paginator.page(page)
        skus = page.object_list
        current_page = page.number
        total_page = paginator.num_pages


        skus_list = []
        for sku in skus:
            spus = SPU.objects.filter(id=sku.spu_id)
            #spus = sku.sPU_set.all()
            spus_list = []
            for spu in spus:
                spu_data_dict = {
                    'name': spu.name,
                    'brand': spu.brand,
                    'category1_id': spu.category1_id,
                    'category2_id': spu.category2_id,
                    'category3_id': spu.category2_id,
                    'sales': spu.sales,
                    'comments': spu.comments,
                    'desc_detail': spu.desc_detail,
                    'desc_pack': spu.desc_pack,
                    'desc_service': spu.desc_service,
                }

                spus_list.append(spu_data_dict)


            #categories = sku.category_set.all()
            # categories_2 = GoodsCategory.objects.filter(id=sku.category_id)
            # categories_2_list = []
            # for category_2 in categories_2:
            #     category_2.subs = category_2.subs.all()
            #     category2_dict_data = {
            #         'name': category_2.name,
            #         'parent_id': category_2.parent_id,
            #
            #     }
            #
            #     categories_2_list.append(category2_dict_data)

            category_result = GoodsCategory.objects.get(id=sku.category_id)
            category_2 = {
                "id": category_result.id,
                'name': category_result.name,
            }


            dict_data = {
                'id': sku.id,
                'name': sku.name,
                'caption': sku.caption,
                'sku_id': sku.id,
                'category_id': sku.category_id,
                'price': sku.price,
                'cost_price': sku.cost_price,
                'market_price': sku.market_price,
                'stock': sku.stock,
                'sales': sku.sales,
                'is_launched': sku.is_launched,
                'default_image_url': sku.default_image_url
            }

            dict_data['spu'] = skus_list
            skus_list.append(dict_data)

        print(skus_list)

        context = {
            "categories": categories,
            "skus": skus_list,
            "category": category_result,
            "current_page": current_page,
            "total_page": total_page,
            "sort": sort,
        }
        return render(request, 'list.html', context=context)



class HotSkuView(View):
    def get(self, request, category_id):
        skus = SKU.objects.filter(category_id=category_id).all()[:constants.SKU_HOT_COUNT]
        hot_sku_list = []
        for sku in skus:
            sku_data_dict = {
                'image_url': sku.default_image_url.url,
                "name": sku.name,
                "price": sku.price,
            }

            hot_sku_list.append(sku_data_dict)

        print(hot_sku_list)
        return http.JsonResponse({"hot_sku_list" : hot_sku_list})


# class SKUDetailView(View):
#     def get(self, request, sku_id):
#         categories = get_categories()
#
#         sku = SKU.objects.get(id=sku_id)
#         category = sku.category
#
#         context = {
#             "categories": categories,
#             "category": category,
#             "sku": sku,
#         }
#         return render(request, 'detail.html', context=context)


#3, 商品详情页
class SKUDetailView(View):
    def get(self,request,sku_id):
        #1, 获取商品分类
        categories = get_categories()

        #2, 获取面包屑需要的数据
        sku = SKU.objects.get(id=sku_id)
        category = sku.category

        #3, 商品规格信息
        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options


        #拼接数据
        context = {
            "categories":categories,
            "category":category,
            "sku":sku,
            "specs":goods_specs
        }
        return render(request,'detail.html',context=context)


#4, 统计商品分类访问量
class CategoryVisitCountView(View):
    def post(self,request,category_id):
        #1, 获取当天时间
        today = datetime.today()

        #2, 查询分类访问量对象
        try:
            category_visit_count = CategoryVisitCount.objects.get(date=today, category_id=category_id)
        except Exception as e:
            category_visit_count = CategoryVisitCount()

        #3, 设置访问数据,入库
        category_visit_count.date = today
        category_visit_count.category_id = category_id
        category_visit_count.count += 1
        category_visit_count.save()

        #4, 返回响应
        return http.JsonResponse({"code":RET.OK})

#5, 用户浏览历史记录
class BrowseHistoryView(LoginRequiredView):
    def post(self,request):
        #1,获取参数
        dict_data = json.loads(request.body.decode())
        sku_id = dict_data.get("sku_id")

        #2,校验参数
        if not sku_id:
            return http.JsonResponse({"code":RET.PARAMERR})

        #3,数据入库(redis)
        #3,1 去重
        redis_conn = get_redis_connection("history")
        redis_conn.lrem("history_%s"%request.user.id,0,sku_id)

        #3,2 存储
        redis_conn.lpush("history_%s"%request.user.id,sku_id)

        #3,3 截取
        redis_conn.ltrim("history_%s"%request.user.id,0,4)

        #4,返回响应
        return http.JsonResponse({"code":RET.OK})

    def get(self,request):

        #1,获取redis中的浏览记录
        redis_conn = get_redis_connection("history")
        sku_ids = redis_conn.lrange("history_%s"%request.user.id,0,-1)

        #2,拼接数据
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "id":sku.id,
                "default_image_url":sku.default_image_url.url,
                "name":sku.name,
                "price":sku.price
            }
            sku_list.append(sku_dict)

        #3,返回响应
        return http.JsonResponse({"skus":sku_list,"code":RET.OK})





















